import React, { useState, useEffect, useCallback } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Typography,
  Drawer,
  Statistic,
  Tabs,
  Empty,
  theme,
  Descriptions,
  Badge,
  Divider,
  Spin,
} from "antd";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ReferenceLine,
  Brush,
} from "recharts";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SettingOutlined,
  EyeOutlined,
  DatabaseOutlined,
  ExperimentOutlined,
  SearchOutlined,
  FileTextOutlined,
  CopyOutlined,
  ReloadOutlined,
  LineChartOutlined,
  CodeOutlined,
} from "@ant-design/icons";
import { useTranslation } from "react-i18next";
import { useMessage } from "../contexts/MessageContext";
import { useWindowSize } from "../hooks/useWindowSize";
import { deviceAPI, dataAPI, cmdAPI } from "../services/api";
import dayjs from "dayjs";

const { Title, Text } = Typography;
const { Option } = Select;

const DeviceManagement = () => {
  const { t } = useTranslation();
  const { token } = theme.useToken();
  const { messageApi } = useMessage();
  const { isMobile } = useWindowSize();
  const [devices, setDevices] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingDevice, setEditingDevice] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // 设备详情相关状态
  const [detailDrawerVisible, setDetailDrawerVisible] = useState(false);
  const [selectedDevice, setSelectedDevice] = useState(null);
  const [deviceData, setDeviceData] = useState([]);
  const [deviceDataPagination, setDeviceDataPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [tempHumidityData, setTempHumidityData] = useState([]);
  const [tempHumidityPagination, setTempHumidityPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [deviceParams, setDeviceParams] = useState([]);
  const [deviceParamsPagination, setDeviceParamsPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [originDataByType, setOriginDataByType] = useState({}); // 按类型存储原始数据 {1: [], 2: [], ...}
  const [originDataLoading, setOriginDataLoading] = useState({}); // 各类型加载状态 {1: false, 2: true, ...}
  const [activeOriginTab, setActiveOriginTab] = useState("type-1"); // 当前激活的原始数据tab
  const [detailLoading, setDetailLoading] = useState(false);
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState({});
  const [nextRefreshTime, setNextRefreshTime] = useState(null);

  // CMD指令管理相关状态
  const [cmdList, setCmdList] = useState([]);
  const [cmdPagination, setCmdPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [cmdLoading, setCmdLoading] = useState(false);
  const [cmdModalVisible, setCmdModalVisible] = useState(false);
  const [cmdForm] = Form.useForm();

  // 可视化相关状态
  const [visualizationModalVisible, setVisualizationModalVisible] =
    useState(false);
  const [visualizationDevice, setVisualizationDevice] = useState(null);
  const [visualizationData, setVisualizationData] = useState([]);
  const [visualizationLoading, setVisualizationLoading] = useState(false);

  // 获取指定类型的原始数据
  const fetchOriginDataByType = useCallback(
    async (device, type, forceRefresh = false) => {
      setOriginDataLoading((prev) => ({ ...prev, [type]: true }));

      try {
        const response = await dataAPI.getGhyDeviceOriginData({
          batch: device.batch,
          code: device.code,
          type: type, // 传递具体的类型参数
          pageNo: 1,
          pageSize: 100,
        });

        const data = response?.data?.list || [];
        setOriginDataByType((prev) => ({
          ...prev,
          [type]: data,
        }));

        if (data.length === 0) {
          messageApi.info(`暂无类型 ${type} 的原始数据`);
        } else if (forceRefresh) {
          messageApi.success(`已刷新类型 ${type} 的数据`);
        }
      } catch (error) {
        console.error(`获取类型 ${type} 原始数据失败:`, error);
        messageApi.warning(`获取类型 ${type} 原始数据失败`);
        setOriginDataByType((prev) => ({
          ...prev,
          [type]: [],
        }));
      } finally {
        setOriginDataLoading((prev) => ({ ...prev, [type]: false }));
      }
    },
    [messageApi]
  );

  // 首次打开原始数据时自动加载第一个tab的数据
  useEffect(() => {
    if (
      selectedDevice &&
      detailDrawerVisible &&
      Object.keys(originDataByType).length === 0
    ) {
      const isLoading = originDataLoading[1];
      const hasData = originDataByType[1] && originDataByType[1].length > 0;
      if (!isLoading && !hasData) {
        fetchOriginDataByType(selectedDevice, 1); // 默认加载第一个类型的数据
      }
    }
  }, [selectedDevice, detailDrawerVisible, fetchOriginDataByType]);

  // MAC地址格式化函数
  const formatMacAddress = (mac) => {
    if (!mac) return "-";
    // 如果已经包含分隔符，直接返回
    if (mac.includes(":") || mac.includes("-")) return mac.toUpperCase();
    // 否则添加冒号分隔符
    return mac.replace(/(.{2})(?=.)/g, "$1:").toUpperCase();
  };

  // MAC地址去格式化函数（用于API请求）
  const unformatMacAddress = (mac) => {
    if (!mac) return "";
    // 移除所有分隔符，返回纯字符串
    return mac.replace(/[:-]/g, "").toUpperCase();
  };

  // MAC地址输入格式化
  const handleMacInputChange = (e) => {
    const value = e.target.value.replace(/[:-]/g, ""); // 先移除所有分隔符
    if (value.length <= 12) {
      const formatted = value.replace(/(.{2})(?=.)/g, "$1:").toUpperCase();
      form.setFieldsValue({ mac: formatted });
    }
  };

  // 字节数据转十六进制函数
  const formatHexData = (uploadData) => {
    if (!Array.isArray(uploadData)) return "";
    return uploadData
      .map((byte) => {
        // 将负数转换为正数的十六进制表示
        const unsignedByte = byte < 0 ? byte + 256 : byte;
        return unsignedByte.toString(16).toUpperCase().padStart(2, "0");
      })
      .join(" ");
  };

  // 复制到剪贴板函数
  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      messageApi.success("已复制到剪贴板");
    } catch (error) {
      console.error("复制失败:", error);
      // 降级方案：使用旧方法
      const textArea = document.createElement("textarea");
      textArea.value = text;
      document.body.appendChild(textArea);
      textArea.select();
      try {
        document.execCommand("copy");
        messageApi.success("已复制到剪贴板");
      } catch (fallbackError) {
        messageApi.error("复制失败");
      }
      document.body.removeChild(textArea);
    }
  };

  // 时间格式化函数
  const formatTimestamp = (timestamp, format = "YYYY-MM-DD HH:mm") => {
    if (!timestamp) return "-";

    if (typeof timestamp === "number") {
      // 如果是10位数字，说明是秒级时间戳
      if (timestamp.toString().length === 10) {
        return dayjs.unix(timestamp).format(format);
      }
      // 如果是13位数字，说明是毫秒级时间戳
      else if (timestamp.toString().length === 13) {
        return dayjs(timestamp).format(format);
      }
    }
    // 处理字符串格式的时间
    return dayjs(timestamp).format(format);
  };

  // 16进制验证函数
  const isValidHex = (value) => {
    if (!value) return false;
    // 只允许0-9和a-f/A-F的字符
    return /^[0-9a-fA-F]+$/.test(value);
  };

  // 获取设备数据（支持分页）
  const fetchDeviceData = useCallback(
    async (device, pageNo = 1, pageSize = 20) => {
      if (!device) return;

      try {
        const response = await dataAPI.getDeviceDataList({
          sample: device.sample,
          batch: device.batch,
          code: device.code,
          pageNo: pageNo,
          pageSize: pageSize,
        });

        const list = response?.data?.list || [];
        const totalCount = response?.data?.totalCount || 0;

        setDeviceData(list);
        setDeviceDataPagination({
          current: pageNo,
          pageSize: pageSize,
          total: totalCount,
        });
      } catch (error) {
        console.error("获取设备数据失败:", error);
        messageApi.warning("获取设备数据失败");
        setDeviceData([]);
        setDeviceDataPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }
    },
    [messageApi]
  );

  // 设备数据表格分页切换
  const handleDeviceDataTableChange = (newPagination) => {
    if (selectedDevice) {
      fetchDeviceData(
        selectedDevice,
        newPagination.current,
        newPagination.pageSize
      );
    }
  };

  // 获取温湿度数据（支持分页）
  const fetchTempHumidityData = useCallback(
    async (device, pageNo = 1, pageSize = 20) => {
      if (!device) return;

      try {
        const response = await dataAPI.getDeviceTmpRHList({
          sample: device.sample,
          batch: device.batch,
          code: device.code,
          pageNo: pageNo,
          pageSize: pageSize,
        });

        const list = response?.data?.list || [];
        const totalCount = response?.data?.totalCount || 0;

        setTempHumidityData(list);
        setTempHumidityPagination({
          current: pageNo,
          pageSize: pageSize,
          total: totalCount,
        });
      } catch (error) {
        console.error("获取温湿度数据失败:", error);
        messageApi.warning("获取温湿度数据失败");
        setTempHumidityData([]);
        setTempHumidityPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }
    },
    [messageApi]
  );

  // 温湿度表格分页切换
  const handleTempHumidityTableChange = (newPagination) => {
    if (selectedDevice) {
      fetchTempHumidityData(
        selectedDevice,
        newPagination.current,
        newPagination.pageSize
      );
    }
  };

  // 获取设备参数（支持分页）
  const fetchDeviceParams = useCallback(
    async (device, pageNo = 1, pageSize = 20) => {
      if (!device) return;

      try {
        const response = await dataAPI.getDeviceParamList({
          sample: device.sample,
          batch: device.batch,
          code: device.code,
          pageNo: pageNo,
          pageSize: pageSize,
        });

        const list = response?.data?.list || [];
        const totalCount = response?.data?.totalCount || 0;

        setDeviceParams(list);
        setDeviceParamsPagination({
          current: pageNo,
          pageSize: pageSize,
          total: totalCount,
        });
      } catch (error) {
        console.error("获取设备参数失败:", error);
        messageApi.warning("获取设备参数失败");
        setDeviceParams([]);
        setDeviceParamsPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }
    },
    [messageApi]
  );

  // 设备参数表格分页切换
  const handleDeviceParamsTableChange = (newPagination) => {
    if (selectedDevice) {
      fetchDeviceParams(
        selectedDevice,
        newPagination.current,
        newPagination.pageSize
      );
    }
  };

  // 获取CMD指令列表（支持分页）
  const fetchCmdList = useCallback(
    async (device, pageNo = 1, pageSize = 20) => {
      if (!device) return;

      setCmdLoading(true);
      try {
        const response = await cmdAPI.queryCmds({
          batch: device.batch,
          code: device.code,
          pageNo: pageNo,
          pageSize: pageSize,
        });

        // 检查响应格式：可能是 { code: 0, msg: "操作成功", data: [...] } 或带分页的格式
        const data = response?.data;

        if (Array.isArray(data)) {
          // 如果data是数组，说明没有分页信息，全部数据一次返回
          setCmdList(data);
          setCmdPagination({
            current: 1,
            pageSize: data.length || 20,
            total: data.length,
          });
        } else if (data && data.list) {
          // 如果data是对象且包含list，说明有分页信息
          setCmdList(data.list || []);
          setCmdPagination({
            current: pageNo,
            pageSize: pageSize,
            total: data.totalCount || 0,
          });
        } else {
          setCmdList([]);
          setCmdPagination({
            current: 1,
            pageSize: 20,
            total: 0,
          });
        }
      } catch (error) {
        console.error("获取指令列表失败:", error);
        messageApi.warning("获取指令列表失败");
        setCmdList([]);
        setCmdPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      } finally {
        setCmdLoading(false);
      }
    },
    [messageApi]
  );

  // CMD指令表格分页切换
  const handleCmdTableChange = (newPagination) => {
    if (selectedDevice) {
      fetchCmdList(
        selectedDevice,
        newPagination.current,
        newPagination.pageSize
      );
    }
  };

  // 删除指令
  const handleDeleteCmd = async (id) => {
    try {
      await cmdAPI.deleteCmds(id);
      messageApi.success("删除指令成功");
      // 重新加载指令列表
      if (selectedDevice) {
        fetchCmdList(selectedDevice);
      }
    } catch (error) {
      console.error("删除指令失败:", error);
      messageApi.error("删除指令失败");
    }
  };

  // 显示添加指令模态框
  const showCmdModal = () => {
    setCmdModalVisible(true);
    cmdForm.resetFields();
  };

  // 关闭添加指令模态框
  const handleCmdModalCancel = () => {
    setCmdModalVisible(false);
    cmdForm.resetFields();
  };

  // 提交新指令
  const handleCmdSubmit = async () => {
    try {
      const values = await cmdForm.validateFields();

      // 验证16进制格式
      if (!isValidHex(values.cmd)) {
        messageApi.error("指令格式不正确，请输入有效的16进制数据（如：0a0b）");
        return;
      }

      await cmdAPI.sendCmd({
        batch: selectedDevice.batch,
        code: selectedDevice.code,
        cmds: values.cmd,
      });

      messageApi.success("发送指令成功");
      handleCmdModalCancel();
      // 重新加载指令列表
      fetchCmdList(selectedDevice);
    } catch (error) {
      console.error("发送指令失败:", error);
      messageApi.error("发送指令失败");
    }
  };

  // 设备类型选项
  const deviceTypeOptions = [
    { value: 0, label: t("device.deviceTypes.normal") },
    { value: 1, label: t("device.deviceTypes.g4") },
    { value: 2, label: t("device.deviceTypes.gateway") },
  ];

  // 获取设备列表（使用当前状态中的搜索参数）
  const fetchDevices = async (params = {}) => {
    setLoading(true);
    try {
      const response = await deviceAPI.getDeviceList({
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
        pageOrderName: "id",
        pageOrderBy: "desc",
        ...searchParams, // 包含搜索参数
        ...params,
      });

      if (response && response.data) {
        setDevices(response.data.list || []);
        setPagination((prev) => ({
          ...prev,
          total: response.data.totalCount || 0,
        }));
      }
    } catch (error) {
      messageApi.error(t("device.fetchFailed"));
      console.error("获取设备列表错误:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDevices();
  }, []);

  // 自动刷新功能 - 每10分钟刷新一次
  useEffect(() => {
    // 设置下次刷新时间
    const setRefreshTime = () => {
      const nextTime = new Date();
      nextTime.setMinutes(nextTime.getMinutes() + 10);
      setNextRefreshTime(nextTime);
    };

    setRefreshTime();

    // 设置定时器，每10分钟执行一次
    const interval = setInterval(() => {
      console.log("自动刷新设备数据...");
      fetchDevices();
      setRefreshTime();
    }, 10 * 60 * 1000); // 10分钟 = 10 * 60 * 1000毫秒

    // 清理定时器
    return () => {
      clearInterval(interval);
    };
  }, []);

  // 处理表格变化
  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
    // 直接传递新的分页参数，避免异步状态更新问题
    fetchDevicesWithParams({
      pageNo: newPagination.current,
      pageSize: newPagination.pageSize,
      ...searchParams,
    });
  };

  // 打开添加/编辑模态框
  const showModal = (device = null) => {
    setEditingDevice(device);
    setModalVisible(true);
    if (device) {
      // 编辑时需要格式化MAC地址显示
      const formValues = {
        ...device,
        mac: formatMacAddress(device.mac),
      };
      form.setFieldsValue(formValues);
    } else {
      form.resetFields();
    }
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
    setEditingDevice(null);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 处理MAC地址格式 - 去除分隔符
      const submitValues = {
        ...values,
        mac: unformatMacAddress(values.mac),
      };

      if (editingDevice) {
        // 编辑
        await deviceAPI.editGhyDevice({
          id: editingDevice.id,
          ...submitValues,
        });
        messageApi.success(t("device.editSuccess"));
      } else {
        // 添加
        await deviceAPI.addGhyDevice(submitValues);
        messageApi.success(t("device.addSuccess"));
      }

      handleCancel();
      fetchDevices();
    } catch (error) {
      messageApi.error(
        editingDevice ? t("device.editFailed") : t("device.addFailed")
      );
      console.error("提交设备信息错误:", error);
    }
  };

  // 删除设备
  const handleDelete = async (ids) => {
    try {
      await deviceAPI.delGhyDevice(ids);
      messageApi.success(t("device.deleteSuccess"));
      fetchDevices();
    } catch (error) {
      messageApi.error(t("device.deleteFailed"));
      console.error("删除设备错误:", error);
    }
  };

  // 获取设备列表（直接传入搜索参数，不依赖状态）
  const fetchDevicesWithParams = async (params = {}) => {
    setLoading(true);
    try {
      const { pageNo, pageSize, ...searchParamsFromParams } = params;
      const response = await deviceAPI.getDeviceList({
        pageNo: pageNo || pagination.current,
        pageSize: pageSize || pagination.pageSize,
        pageOrderName: "id",
        pageOrderBy: "desc",
        ...searchParamsFromParams, // 直接使用传入的搜索参数
      });

      if (response && response.data) {
        setDevices(response.data.list || []);
        setPagination((prev) => ({
          ...prev,
          current: pageNo || prev.current,
          total: response.data.totalCount || 0,
        }));
      }
    } catch (error) {
      messageApi.error(t("device.fetchFailed"));
      console.error("获取设备列表错误:", error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索功能
  const handleSearch = (values) => {
    const searchData = {};

    // 样地编号搜索（确保为整数，允许输入0）
    if (typeof values.sample === "number") {
      searchData.sample = parseInt(values.sample);
    }

    // 设备类型搜索
    if (values.type !== undefined && values.type !== null) {
      searchData.type = values.type;
    }

    // 设备批次号搜索（确保为整数，允许输入0）
    if (typeof values.batch === "number") {
      searchData.batch = parseInt(values.batch);
    }

    // 设备编号搜索（确保为整数，允许输入0）
    if (typeof values.code === "number") {
      searchData.code = parseInt(values.code);
    }

    // 注意：实际API中设备数据没有MAC地址字段

    setSearchParams(searchData);
    setPagination((prev) => ({ ...prev, current: 1 })); // 重置到第一页

    // 直接使用新的搜索参数，而不是依赖状态更新
    fetchDevicesWithParams({ pageNo: 1, ...searchData });
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination((prev) => ({ ...prev, current: 1 }));
    // 直接传入空的搜索参数
    fetchDevicesWithParams({ pageNo: 1 });
  };
  // 可视化功能
  const handleVisualization = async (device) => {
    setVisualizationDevice(device);
    setVisualizationModalVisible(true);
    setVisualizationLoading(true);

    try {
      // 获取设备数据用于可视化
      const response = await dataAPI.getDeviceDataList({
        sample: device.sample,
        batch: device.batch,
        code: device.code,
        pageNo: 1,
        pageSize: 50, // 获取更多数据点用于图表显示
      });

      const data = response?.data?.list || [];

      // 处理数据格式，适配图表显示
      const chartData = data
        .map((item) => {
          const voltage =
            item.voltage !== undefined && item.voltage !== null
              ? Number((item.voltage / 100).toFixed(2))
              : null;
          const mesa =
            item.mesa !== undefined && item.mesa !== null ? item.mesa : null;
          const temperature =
            item.tmp !== undefined && item.tmp !== null
              ? Number((item.tmp / 100).toFixed(1))
              : null;
          const angle =
            item.angle !== undefined && item.angle !== null ? item.angle : null;
          const rssi =
            item.rssi !== undefined && item.rssi !== null ? item.rssi : null;

          // 判断各指标是否正常
          const voltageThreshold = device.type === 0 ? 3.0 : 6.0;
          const isVoltageNormal =
            voltage !== null ? voltage >= voltageThreshold : null;
          const isMesaNormal = mesa !== null ? mesa >= 0 && mesa <= 2 : null;
          const isTemperatureNormal =
            temperature !== null ? temperature <= 40 : null;
          const isAngleNormal = angle !== null ? true : null; // 角度默认都正常，可根据实际需求调整
          const isRssiNormal = rssi !== null ? rssi >= -80 : null; // RSSI -80以上为正常

          return {
            time: formatTimestamp(item.updatedAt, "MM-DD HH:mm"),
            fullTime: formatTimestamp(item.updatedAt, "YYYY-MM-DD HH:mm:ss"),
            voltage: voltage,
            isVoltageNormal: isVoltageNormal,
            mesa: mesa,
            isMesaNormal: isMesaNormal,
            angle: angle,
            isAngleNormal: isAngleNormal,
            temperature: temperature,
            isTemperatureNormal: isTemperatureNormal,
            rssi: rssi,
            isRssiNormal: isRssiNormal,
            timestamp: item.updatedAt,
          };
        })
        .filter(
          (item) =>
            item.voltage !== null ||
            item.mesa !== null ||
            item.angle !== null ||
            item.temperature !== null ||
            item.rssi !== null
        ) // 过滤掉空数据，但保留0值
        .sort((a, b) => a.timestamp - b.timestamp); // 按时间排序

      // 强制添加测试数据（用于验证功能）
      if (false) {
        // 临时改为 true 强制显示测试数据
        const testData = [
          {
            mesa: 1.0, // 正常
            voltage: 3.5, // 正常
            angle: 45, // 正常
            temperature: 25.5, // 正常
            rssi: -65, // 正常
            time: new Date(Date.now() - 420000), // 7分钟前
          },
          {
            mesa: 1.2, // 正常
            voltage: 3.2, // 正常
            angle: 90, // 正常
            temperature: 35.0, // 正常
            rssi: -75, // 正常
            time: new Date(Date.now() - 360000), // 6分钟前
          },
          {
            mesa: -39, // 异常
            voltage: 2.5, // 异常
            angle: 180, // 正常
            temperature: 50.0, // 异常
            rssi: -95, // 异常
            time: new Date(Date.now() - 300000), // 5分钟前
          },
          {
            mesa: -20, // 异常
            voltage: 2.8, // 异常
            angle: 270, // 正常
            temperature: 45.5, // 异常
            rssi: -85, // 异常
            time: new Date(Date.now() - 240000), // 4分钟前
          },
          {
            mesa: 1.5, // 正常
            voltage: 3.8, // 正常
            angle: 30, // 正常
            temperature: 28.0, // 正常
            rssi: -60, // 正常
            time: new Date(Date.now() - 180000), // 3分钟前
          },
          {
            mesa: 3.5, // 异常
            voltage: 4.2, // 正常
            angle: 120, // 正常
            temperature: 42.0, // 异常
            rssi: -70, // 正常
            time: new Date(Date.now() - 120000), // 2分钟前
          },
          {
            mesa: 0.5, // 正常
            voltage: 3.6, // 正常
            angle: 60, // 正常
            temperature: 32.0, // 正常
            rssi: -78, // 正常
            time: new Date(Date.now() - 60000), // 1分钟前
          },
          {
            mesa: -10, // 异常
            voltage: 2.2, // 异常
            angle: 200, // 正常
            temperature: 55.0, // 异常
            rssi: -100, // 异常
            time: new Date(), // 现在
          },
        ];

        testData.forEach((test) => {
          // 计算各指标是否正常
          const voltageThreshold = device.type === 0 ? 3.0 : 6.0;
          const isVoltageNormal = test.voltage >= voltageThreshold;
          const isMesaNormal = test.mesa >= 0 && test.mesa <= 2;
          const isTemperatureNormal = test.temperature <= 40;
          const isAngleNormal = true; // 角度默认都正常
          const isRssiNormal = test.rssi >= -80;

          chartData.push({
            time: formatTimestamp(test.time, "MM-DD HH:mm"),
            fullTime: formatTimestamp(test.time, "YYYY-MM-DD HH:mm:ss"),
            mesa: test.mesa,
            isMesaNormal: isMesaNormal,
            voltage: test.voltage,
            isVoltageNormal: isVoltageNormal,
            angle: test.angle,
            isAngleNormal: isAngleNormal,
            temperature: test.temperature,
            isTemperatureNormal: isTemperatureNormal,
            rssi: test.rssi,
            isRssiNormal: isRssiNormal,
            timestamp: test.time.getTime(),
          });
        });
      }

      // 重新按时间排序所有数据（包括测试数据）
      chartData.sort((a, b) => a.timestamp - b.timestamp);

      setVisualizationData(chartData);

      if (chartData.length === 0) {
        messageApi.info("暂无该设备的传感器数据用于可视化");
      }
    } catch (error) {
      console.error("获取可视化数据失败:", error);
      messageApi.error("获取可视化数据失败");
      setVisualizationData([]);
    } finally {
      setVisualizationLoading(false);
    }
  };
  // 查看设备详情
  const handleViewDetail = async (device) => {
    setSelectedDevice(device);
    setDetailDrawerVisible(true);
    setDetailLoading(true);

    // 为每个API调用添加独立的错误处理
    const fetchWithErrorHandling = async (apiCall, dataType) => {
      try {
        const response = await apiCall();
        return response?.data?.list || [];
      } catch (error) {
        console.error(`获取${dataType}数据失败:`, error);
        messageApi.warning(`获取${dataType}数据失败，显示其他可用数据`);
        return []; // 返回空数组而不是抛出错误
      }
    };

    try {
      // 重置原始数据状态
      setOriginDataByType({});
      setOriginDataLoading({});
      setActiveOriginTab("type-1"); // 重置激活的tab

      // 使用专门的函数获取各类数据（支持分页）
      fetchDeviceData(device, 1, 20);
      fetchTempHumidityData(device, 1, 20);
      fetchDeviceParams(device, 1, 20);

      // 如果是网关设备（type === 2），加载CMD指令列表
      if (device.type === 2) {
        fetchCmdList(device, 1, 20);
      } else {
        setCmdList([]);
        setCmdPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }

      // 数据已在各自的fetch函数中异步加载，不需要在此检查
    } catch (error) {
      // 这里处理Promise.all整体失败的情况（理论上不应该发生，因为我们已经在每个API中处理了错误）
      console.error("获取设备详情数据失败:", error);
      messageApi.error("获取设备详情数据失败");

      // 即使出错也要设置空数组，避免显示旧数据
      setDeviceData([]);
      setDeviceDataPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
      setTempHumidityData([]);
      setTempHumidityPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
      setDeviceParams([]);
      setDeviceParamsPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
      setCmdList([]);
      setCmdPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
      setOriginDataByType({});
      setOriginDataLoading({});
      setActiveOriginTab("type-1");
    } finally {
      setDetailLoading(false);
    }
  };

  // 解析设备参数JSON (备用函数，当前使用deviceParams数组)
  const parseDeviceParams = (paramString, deviceUpdatedAt) => {
    if (!paramString) return [];

    try {
      const params = JSON.parse(paramString);
      const paramList = [];

      const paramNames = {
        scanTime: "扫描时间",
        netOverTime: "网络超时",
        waywakeup: "唤醒间隔",
        nextwakeup: "下次唤醒",
        dbpower: "发射功率",
      };

      const paramUnits = {
        scanTime: "秒",
        netOverTime: "毫秒",
        waywakeup: "秒",
        nextwakeup: "时间戳",
        dbpower: "dBm",
      };

      Object.keys(params).forEach((key, index) => {
        let value = params[key];
        let displayValue = value;

        // 特殊处理时间戳
        if (key === "nextwakeup" && value) {
          displayValue = formatTimestamp(value, "YYYY-MM-DD HH:mm:ss");
        }

        paramList.push({
          id: `param_${index}`,
          paramName: paramNames[key] || key,
          paramValue: displayValue,
          unit: paramUnits[key] || "",
          updatedAt: deviceUpdatedAt || Date.now(),
        });
      });

      return paramList;
    } catch (error) {
      console.error("解析设备参数失败:", error);
      return [];
    }
  };

  // 获取设备类型标签
  const getDeviceTypeTag = (type) => {
    const typeMap = {
      0: { color: "blue", text: t("device.deviceTypes.normal") },
      1: { color: "green", text: t("device.deviceTypes.g4") },
      2: { color: "orange", text: t("device.deviceTypes.gateway") },
    };
    const config = typeMap[type] || { color: "default", text: "Unknown" };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取原始数据类型标签
  const getOriginDataTypeTag = (type) => {
    const typeMap = {
      1: { color: "blue", text: "设备数据" },
      2: { color: "green", text: "温湿度" },
      3: { color: "orange", text: "基本信息" },
      4: { color: "purple", text: "4G测量设备" },
      5: { color: "cyan", text: "上报数据" },
      6: { color: "magenta", text: "固件信息" },
    };
    const config = typeMap[type] || {
      color: "default",
      text: `未知类型(${type})`,
    };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 表格列定义
  const columns = [
    {
      title: t("device.sampleCode"),
      dataIndex: "sample",
      key: "sample",
    },
    {
      title: t("device.deviceType"),
      dataIndex: "type",
      key: "type",
      render: (type) => getDeviceTypeTag(type),
    },
    {
      title: t("device.batchNumber"),
      dataIndex: "batch",
      key: "batch",
    },
    {
      title: t("device.deviceCode"),
      dataIndex: "code",
      key: "code",
    },
    {
      title: "MAC地址",
      dataIndex: "mac",
      key: "mac",
      render: (mac) => formatMacAddress(mac),
    },
    {
      title: t("device.createTime"),
      dataIndex: "updatedAt",
      key: "updatedAt",
      render: (updatedAt) => formatTimestamp(updatedAt, "YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: t("device.operation"),
      key: "action",
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<LineChartOutlined />}
            onClick={() => handleVisualization(record)}
          >
            可视化
          </Button>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            {t("common.edit")}
          </Button>
          <Popconfirm
            title={t("device.deleteConfirm")}
            onConfirm={() => handleDelete(record.id)}
            okText={t("common.confirm")}
            cancelText={t("common.cancel")}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              {t("common.delete")}
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Space align="center">
            <SettingOutlined style={{ fontSize: 24, color: "#52c41a" }} />
            <Title level={2} style={{ margin: 0 }}>
              {t("device.title")}
            </Title>
          </Space>
        </Col>
        <Col>
          <Space align="center" size="large">
            {nextRefreshTime && (
              <div style={{ textAlign: "right" }}>
                <Text type="secondary" style={{ fontSize: "12px" }}>
                  🔄 下次刷新: {formatTimestamp(nextRefreshTime, "HH:mm:ss")}
                </Text>
                <br />
                <Text type="secondary" style={{ fontSize: "11px" }}>
                  平均采集间隔: 10分钟
                </Text>
              </div>
            )}
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => showModal()}
              size="large"
              style={{
                borderRadius: 8,
                height: 40,
                paddingLeft: 20,
                paddingRight: 20,
              }}
            >
              {t("device.addDevice")}
            </Button>
          </Space>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <div
        style={{
          marginBottom: 24,
          padding: "20px 0",
          borderBottom: "1px solid #f0f0f0",
        }}
      >
        <Form
          form={searchForm}
          onFinish={handleSearch}
          style={{ width: "100%" }}
        >
          <Row gutter={[24, 16]} align="bottom">
            <Col xs={24} sm={12} md={6} lg={4}>
              <Form.Item
                name="sample"
                label={
                  <span
                    style={{
                      fontSize: "14px",
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    样地编号
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <InputNumber
                  placeholder="请输入样地编号"
                  controls={false}
                  size="large"
                  min={0}
                  precision={0}
                  style={{
                    width: "100%",
                    borderRadius: 8,
                    border: "1px solid #d9d9d9",
                    transition: "all 0.3s",
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6} lg={4}>
              <Form.Item
                name="type"
                label={
                  <span
                    style={{
                      fontSize: "14px",
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    设备类型
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <Select
                  placeholder="请选择设备类型"
                  allowClear
                  size="large"
                  style={{
                    borderRadius: 8,
                  }}
                >
                  <Option value={0}>普通设备</Option>
                  <Option value={1}>4G设备</Option>
                  <Option value={2}>网关设备</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6} lg={4}>
              <Form.Item
                name="batch"
                label={
                  <span
                    style={{
                      fontSize: "14px",
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    设备批次号
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <InputNumber
                  placeholder="请输入批次号"
                  controls={false}
                  size="large"
                  min={0}
                  precision={0}
                  style={{
                    width: "100%",
                    borderRadius: 8,
                    border: "1px solid #d9d9d9",
                    transition: "all 0.3s",
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={6} lg={4}>
              <Form.Item
                name="code"
                label={
                  <span
                    style={{
                      fontSize: "14px",
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    设备编号
                  </span>
                }
                style={{ marginBottom: 0 }}
              >
                <InputNumber
                  placeholder="请输入设备编号"
                  controls={false}
                  size="large"
                  min={0}
                  precision={0}
                  style={{
                    width: "100%",
                    borderRadius: 8,
                    border: "1px solid #d9d9d9",
                    transition: "all 0.3s",
                  }}
                />
              </Form.Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={8}>
              <Form.Item style={{ marginBottom: 0 }}>
                <Space size="middle">
                  <Button
                    type="primary"
                    htmlType="submit"
                    icon={<SearchOutlined />}
                    size="large"
                    style={{
                      borderRadius: 8,
                      height: 40,
                      paddingLeft: 24,
                      paddingRight: 24,
                      fontWeight: 500,
                      boxShadow: "0 2px 4px rgba(24, 144, 255, 0.3)",
                      border: "none",
                    }}
                  >
                    搜索
                  </Button>
                  <Button
                    onClick={handleReset}
                    size="large"
                    style={{
                      borderRadius: 8,
                      height: 40,
                      paddingLeft: 24,
                      paddingRight: 24,
                      fontWeight: 500,
                      color: token.colorTextSecondary,
                      borderColor: "#d9d9d9",
                    }}
                  >
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>

      <Table
        columns={columns}
        dataSource={devices}
        rowKey="id"
        loading={loading}
        size={isMobile ? "small" : "middle"}
        pagination={
          isMobile
            ? {
                ...pagination,
                showSizeChanger: false,
                showQuickJumper: false,
                showTotal: (total, range) => `${range[0]}-${range[1]}/${total}`,
                simple: true,
                size: "small",
              }
            : {
                ...pagination,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `${t("common.total")} ${range[0]}-${range[1]} ${t(
                    "common.items"
                  )}/${total} ${t("common.items")}`,
              }
        }
        onChange={handleTableChange}
        scroll={{ x: isMobile ? 700 : 1000 }}
        style={{
          borderRadius: 8,
        }}
      />

      <Modal
        title={editingDevice ? t("device.editDevice") : t("device.addDevice")}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={handleCancel}
        width={700}
        destroyOnHidden
        style={{
          borderRadius: 12,
        }}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 0,
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t("device.sampleCode")}
                name="sample"
                rules={[
                  { required: true, message: "请输入样地编号" },
                  { type: "number", message: "样地编号必须为数字" },
                ]}
              >
                <InputNumber
                  style={{ width: "100%" }}
                  placeholder="请输入样地编号"
                  min={1}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t("device.deviceType")}
                name="type"
                rules={[{ required: true, message: "请选择设备类型" }]}
              >
                <Select placeholder="请选择设备类型">
                  {deviceTypeOptions.map((option) => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t("device.batchNumber")}
                name="batch"
                rules={[
                  { required: true, message: "请输入设备批次号" },
                  { type: "number", message: "设备批次号必须为数字" },
                ]}
              >
                <InputNumber
                  style={{ width: "100%" }}
                  placeholder="请输入设备批次号"
                  min={1}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t("device.deviceCode")}
                name="code"
                rules={[
                  { required: true, message: "请输入设备编号" },
                  { type: "number", message: "设备编号必须为数字" },
                ]}
              >
                <InputNumber
                  style={{ width: "100%" }}
                  placeholder="请输入设备编号"
                  min={1}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="MAC地址"
                name="mac"
                rules={[
                  { required: true, message: "请输入MAC地址" },
                  {
                    pattern: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
                    message: "请输入正确的MAC地址格式 (如: AA:BB:CC:DD:EE:FF)",
                  },
                ]}
              >
                <Input
                  style={{ width: "100%" }}
                  placeholder="请输入MAC地址 (如: AABBCCDDEEFF)"
                  maxLength={17}
                  onChange={handleMacInputChange}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 可视化模态框 */}
      <Modal
        title={
          <Space>
            <DatabaseOutlined style={{ color: "#52c41a" }} />
            设备数据可视化 - {visualizationDevice?.code}
          </Space>
        }
        open={visualizationModalVisible}
        onCancel={() => setVisualizationModalVisible(false)}
        width={1200}
        footer={null}
        style={{ top: 20 }}
        styles={{
          body: {
            maxHeight: "80vh",
            overflowY: "auto",
            padding: "24px",
          },
        }}
        wrapClassName="visualization-modal-wrapper"
        destroyOnClose
      >
        {visualizationDevice && (
          <div
            style={{ outline: "none", border: "none" }}
            onMouseDown={(e) => e.preventDefault()}
            onFocus={(e) => e.preventDefault()}
          >
            {/* 设备信息 */}
            <Card size="small" style={{ marginBottom: "24px" }}>
              <Row gutter={[16, 8]}>
                <Col span={6}>
                  <Statistic
                    title="设备编号"
                    value={visualizationDevice.code}
                  />
                </Col>
                <Col span={6}>
                  <Statistic
                    title="样地编号"
                    value={visualizationDevice.sample}
                  />
                </Col>
                <Col span={6}>
                  <Statistic title="批次号" value={visualizationDevice.batch} />
                </Col>
                <Col span={6}>
                  <div>
                    <div
                      style={{
                        color: "#8c8c8c",
                        fontSize: "14px",
                        marginBottom: "4px",
                      }}
                    >
                      设备类型
                    </div>
                    {getDeviceTypeTag(visualizationDevice.type)}
                  </div>
                </Col>
              </Row>
            </Card>

            {/* 图表内容 */}
            <Spin spinning={visualizationLoading}>
              {visualizationData.length > 0 ? (
                <div>
                  <Tabs
                    type="card"
                    size="large"
                    style={{ outline: "none" }}
                    items={[
                      {
                        key: "voltage",
                        label: (
                          <Space>
                            <span style={{ color: "#1890ff" }}>⚡</span>
                            电压折线图
                          </Space>
                        ),
                        children: (
                          <Card title="电压变化趋势" size="small">
                            <div
                              style={{ outline: "none" }}
                              onFocus={(e) => e.preventDefault()}
                            >
                              <ResponsiveContainer
                                width="100%"
                                height={400}
                                style={{ outline: "none", border: "none" }}
                              >
                                <LineChart
                                  data={visualizationData}
                                  style={{ outline: "none", border: "none" }}
                                  onMouseDown={(e) => e.preventDefault()}
                                  margin={{
                                    left: 40,
                                    right: 80,
                                    top: 5,
                                    bottom: 5,
                                  }}
                                >
                                  <CartesianGrid
                                    strokeDasharray="3 3"
                                    stroke="#f0f0f0"
                                  />
                                  <XAxis
                                    dataKey="time"
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={80}
                                  />
                                  <YAxis
                                    tick={{ fontSize: 12 }}
                                    label={{
                                      value: "电压 (V)",
                                      angle: -90,
                                      position: "insideLeft",
                                    }}
                                  />
                                  <Tooltip
                                    formatter={(value, name) => [
                                      value ? `${value}V` : "无数据",
                                      name,
                                    ]}
                                    labelFormatter={(label) =>
                                      `时间: ${
                                        visualizationData.find(
                                          (d) => d.time === label
                                        )?.fullTime || label
                                      }`
                                    }
                                    contentStyle={{
                                      backgroundColor: "#fff",
                                      border: "1px solid #d9d9d9",
                                      borderRadius: "6px",
                                      boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                                    }}
                                  />
                                  <Legend verticalAlign="top" height={36} />
                                  {/* 统一绿色线段，异常数据显示红点 */}
                                  <Line
                                    type="monotone"
                                    dataKey="voltage"
                                    stroke="#52c41a"
                                    strokeWidth={2}
                                    dot={(props) => {
                                      const { cx, cy, payload } = props;
                                      if (
                                        !payload ||
                                        payload.voltage === null ||
                                        payload.voltage === undefined
                                      )
                                        return null;

                                      // 明确判断是否正常
                                      const isNormal =
                                        payload.isVoltageNormal === true;
                                      const color = isNormal
                                        ? "#52c41a"
                                        : "#ff4d4f";
                                      const radius = isNormal ? 4 : 6;

                                      return (
                                        <circle
                                          cx={cx}
                                          cy={cy}
                                          r={radius}
                                          fill={color}
                                          stroke={color}
                                          strokeWidth={2}
                                        />
                                      );
                                    }}
                                    connectNulls={false}
                                    name="电压"
                                  />
                                  <ReferenceLine
                                    y={
                                      visualizationDevice.type === 0 ? 3.0 : 6.0
                                    }
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label={
                                      visualizationDevice.type === 0
                                        ? "不良电压线(3V)"
                                        : "不良电压线(6V)"
                                    }
                                  />
                                  <Brush
                                    dataKey="time"
                                    height={30}
                                    stroke="#1890ff"
                                    alwaysShowText={true}
                                  />
                                </LineChart>
                              </ResponsiveContainer>
                            </div>
                          </Card>
                        ),
                      },
                      {
                        key: "mesa",
                        label: (
                          <Space>
                            <span style={{ color: "#52c41a" }}>📊</span>
                            测量值折线图
                          </Space>
                        ),
                        children: (
                          <Card title="测量值变化趋势" size="small">
                            <div
                              style={{
                                outline: "none",
                                border: "none",
                              }}
                              onFocus={(e) => e.preventDefault()}
                            >
                              <ResponsiveContainer
                                width="100%"
                                height={400}
                                style={{ outline: "none", border: "none" }}
                              >
                                <LineChart
                                  data={visualizationData}
                                  style={{ outline: "none", border: "none" }}
                                  onMouseDown={(e) => e.preventDefault()}
                                  margin={{
                                    left: 40,
                                    right: 80,
                                    top: 5,
                                    bottom: 5,
                                  }}
                                >
                                  <CartesianGrid
                                    strokeDasharray="3 3"
                                    stroke="#f0f0f0"
                                  />
                                  <XAxis
                                    dataKey="time"
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={80}
                                  />
                                  <YAxis
                                    tick={{ fontSize: 12 }}
                                    label={{
                                      value: "测量值",
                                      angle: -90,
                                      position: "insideLeft",
                                    }}
                                    domain={["dataMin-1", "dataMax+1"]}
                                  />
                                  <Tooltip
                                    formatter={(value, name) => [
                                      value || "无数据",
                                      name,
                                    ]}
                                    labelFormatter={(label) =>
                                      `时间: ${
                                        visualizationData.find(
                                          (d) => d.time === label
                                        )?.fullTime || label
                                      }`
                                    }
                                    contentStyle={{
                                      backgroundColor: "#fff",
                                      border: "1px solid #d9d9d9",
                                      borderRadius: "6px",
                                      boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                                    }}
                                  />
                                  <Legend verticalAlign="top" height={36} />
                                  {/* 统一绿色线段，连接所有数据点 */}
                                  <Line
                                    type="monotone"
                                    dataKey="mesa"
                                    stroke="#52c41a"
                                    strokeWidth={2}
                                    dot={(props) => {
                                      const { cx, cy, payload } = props;
                                      if (
                                        !payload ||
                                        payload.mesa === null ||
                                        payload.mesa === undefined
                                      )
                                        return null;

                                      // 明确判断是否正常
                                      const isNormal =
                                        payload.isMesaNormal === true;
                                      const color = isNormal
                                        ? "#52c41a"
                                        : "#ff4d4f";
                                      const radius = isNormal ? 4 : 6;

                                      return (
                                        <circle
                                          cx={cx}
                                          cy={cy}
                                          r={radius}
                                          fill={color}
                                          stroke={color}
                                          strokeWidth={2}
                                        />
                                      );
                                    }}
                                    connectNulls={false}
                                    name="测量值"
                                  />
                                  <ReferenceLine
                                    y={0}
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label="最小正常值"
                                  />
                                  <ReferenceLine
                                    y={2}
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label="最大正常值"
                                  />
                                  <Brush
                                    dataKey="time"
                                    height={30}
                                    stroke="#52c41a"
                                    alwaysShowText={true}
                                  />
                                </LineChart>
                              </ResponsiveContainer>
                            </div>
                          </Card>
                        ),
                      },
                      {
                        key: "angle",
                        label: (
                          <Space>
                            <span style={{ color: "#faad14" }}>📐</span>
                            角度折线图
                          </Space>
                        ),
                        children: (
                          <Card title="角度变化趋势" size="small">
                            <div style={{ outline: "none" }}>
                              <ResponsiveContainer
                                width="100%"
                                height={400}
                                style={{ outline: "none" }}
                              >
                                <LineChart
                                  data={visualizationData}
                                  margin={{
                                    left: 40,
                                    right: 80,
                                    top: 5,
                                    bottom: 5,
                                  }}
                                >
                                  <CartesianGrid
                                    strokeDasharray="3 3"
                                    stroke="#f0f0f0"
                                  />
                                  <XAxis
                                    dataKey="time"
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={80}
                                  />
                                  <YAxis
                                    tick={{ fontSize: 12 }}
                                    label={{
                                      value: "角度 (°)",
                                      angle: -90,
                                      position: "insideLeft",
                                    }}
                                    domain={[0, 360]}
                                  />
                                  <Tooltip
                                    formatter={(value, name) => [
                                      value ? `${value}°` : "无数据",
                                      "角度",
                                    ]}
                                    labelFormatter={(label) =>
                                      `时间: ${
                                        visualizationData.find(
                                          (d) => d.time === label
                                        )?.fullTime || label
                                      }`
                                    }
                                    contentStyle={{
                                      backgroundColor: "#fff",
                                      border: "1px solid #d9d9d9",
                                      borderRadius: "6px",
                                      boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                                    }}
                                  />
                                  <Legend verticalAlign="top" height={36} />
                                  {/* 统一绿色线段，异常数据显示红点 */}
                                  <Line
                                    type="monotone"
                                    dataKey="angle"
                                    stroke="#52c41a"
                                    strokeWidth={2}
                                    dot={(props) => {
                                      const { cx, cy, payload } = props;
                                      if (
                                        !payload ||
                                        payload.angle === null ||
                                        payload.angle === undefined
                                      )
                                        return null;

                                      // 明确判断是否正常
                                      const isNormal =
                                        payload.isAngleNormal === true;
                                      const color = isNormal
                                        ? "#52c41a"
                                        : "#ff4d4f";
                                      const radius = isNormal ? 4 : 6;

                                      return (
                                        <circle
                                          cx={cx}
                                          cy={cy}
                                          r={radius}
                                          fill={color}
                                          stroke={color}
                                          strokeWidth={2}
                                        />
                                      );
                                    }}
                                    connectNulls={false}
                                    name="角度"
                                  />
                                  <ReferenceLine
                                    y={0}
                                    stroke="#d9d9d9"
                                    strokeDasharray="2 2"
                                  />
                                  <ReferenceLine
                                    y={90}
                                    stroke="#d9d9d9"
                                    strokeDasharray="2 2"
                                  />
                                  <ReferenceLine
                                    y={180}
                                    stroke="#d9d9d9"
                                    strokeDasharray="2 2"
                                  />
                                  <ReferenceLine
                                    y={270}
                                    stroke="#d9d9d9"
                                    strokeDasharray="2 2"
                                  />
                                  <Brush
                                    dataKey="time"
                                    height={30}
                                    stroke="#faad14"
                                    alwaysShowText={true}
                                  />
                                </LineChart>
                              </ResponsiveContainer>
                            </div>
                          </Card>
                        ),
                      },
                      {
                        key: "temperature",
                        label: (
                          <Space>
                            <span style={{ color: "#f5222d" }}>🌡️</span>
                            温度折线图
                          </Space>
                        ),
                        children: (
                          <Card title="芯片温度变化趋势" size="small">
                            <div style={{ outline: "none" }}>
                              <ResponsiveContainer
                                width="100%"
                                height={400}
                                style={{ outline: "none" }}
                              >
                                <LineChart
                                  data={visualizationData}
                                  margin={{
                                    left: 40,
                                    right: 80,
                                    top: 5,
                                    bottom: 5,
                                  }}
                                >
                                  <CartesianGrid
                                    strokeDasharray="3 3"
                                    stroke="#f0f0f0"
                                  />
                                  <XAxis
                                    dataKey="time"
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={80}
                                  />
                                  <YAxis
                                    tick={{ fontSize: 12 }}
                                    label={{
                                      value: "温度 (°C)",
                                      angle: -90,
                                      position: "insideLeft",
                                    }}
                                    domain={[0, "dataMax+10"]}
                                  />
                                  <Tooltip
                                    formatter={(value, name) => [
                                      value ? `${value}°C` : "无数据",
                                      name,
                                    ]}
                                    labelFormatter={(label) =>
                                      `时间: ${
                                        visualizationData.find(
                                          (d) => d.time === label
                                        )?.fullTime || label
                                      }`
                                    }
                                    contentStyle={{
                                      backgroundColor: "#fff",
                                      border: "1px solid #d9d9d9",
                                      borderRadius: "6px",
                                      boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                                    }}
                                  />
                                  <Legend verticalAlign="top" height={36} />
                                  {/* 统一绿色线段，异常数据显示红点 */}
                                  <Line
                                    type="monotone"
                                    dataKey="temperature"
                                    stroke="#52c41a"
                                    strokeWidth={2}
                                    dot={(props) => {
                                      const { cx, cy, payload } = props;
                                      if (
                                        !payload ||
                                        payload.temperature === null ||
                                        payload.temperature === undefined
                                      )
                                        return null;

                                      // 明确判断是否正常
                                      const isNormal =
                                        payload.isTemperatureNormal === true;
                                      const color = isNormal
                                        ? "#52c41a"
                                        : "#ff4d4f";
                                      const radius = isNormal ? 4 : 6;

                                      return (
                                        <circle
                                          cx={cx}
                                          cy={cy}
                                          r={radius}
                                          fill={color}
                                          stroke={color}
                                          strokeWidth={2}
                                        />
                                      );
                                    }}
                                    connectNulls={false}
                                    name="温度"
                                  />
                                  <ReferenceLine
                                    y={40}
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label="不良温度"
                                  />
                                  <ReferenceLine
                                    y={60}
                                    stroke="#faad14"
                                    strokeDasharray="5 5"
                                    label="警告温度"
                                  />
                                  <ReferenceLine
                                    y={80}
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label="危险温度"
                                  />
                                  <Brush
                                    dataKey="time"
                                    height={30}
                                    stroke="#f5222d"
                                    alwaysShowText={true}
                                  />
                                </LineChart>
                              </ResponsiveContainer>
                            </div>
                          </Card>
                        ),
                      },
                      {
                        key: "rssi",
                        label: (
                          <Space>
                            <span style={{ color: "#722ed1" }}>📶</span>
                            信号强度折线图
                          </Space>
                        ),
                        children: (
                          <Card title="信号强度变化趋势" size="small">
                            <div style={{ outline: "none" }}>
                              <ResponsiveContainer
                                width="100%"
                                height={400}
                                style={{ outline: "none" }}
                              >
                                <LineChart
                                  data={visualizationData}
                                  margin={{
                                    left: 40,
                                    right: 80,
                                    top: 5,
                                    bottom: 5,
                                  }}
                                >
                                  <CartesianGrid
                                    strokeDasharray="3 3"
                                    stroke="#f0f0f0"
                                  />
                                  <XAxis
                                    dataKey="time"
                                    tick={{ fontSize: 12 }}
                                    angle={-45}
                                    textAnchor="end"
                                    height={80}
                                  />
                                  <YAxis
                                    tick={{ fontSize: 12 }}
                                    label={{
                                      value: "信号强度 (dBm)",
                                      angle: -90,
                                      position: "insideLeft",
                                    }}
                                    domain={[-120, -30]}
                                  />
                                  <Tooltip
                                    formatter={(value, name) => [
                                      value ? `${value}dBm` : "无数据",
                                      "信号强度",
                                    ]}
                                    labelFormatter={(label) =>
                                      `时间: ${
                                        visualizationData.find(
                                          (d) => d.time === label
                                        )?.fullTime || label
                                      }`
                                    }
                                    contentStyle={{
                                      backgroundColor: "#fff",
                                      border: "1px solid #d9d9d9",
                                      borderRadius: "6px",
                                      boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                                    }}
                                  />
                                  <Legend verticalAlign="top" height={36} />
                                  {/* 统一绿色线段，异常数据显示红点 */}
                                  <Line
                                    type="monotone"
                                    dataKey="rssi"
                                    stroke="#52c41a"
                                    strokeWidth={2}
                                    dot={(props) => {
                                      const { cx, cy, payload } = props;
                                      if (
                                        !payload ||
                                        payload.rssi === null ||
                                        payload.rssi === undefined
                                      )
                                        return null;

                                      // 明确判断是否正常
                                      const isNormal =
                                        payload.isRssiNormal === true;
                                      const color = isNormal
                                        ? "#52c41a"
                                        : "#ff4d4f";
                                      const radius = isNormal ? 4 : 6;

                                      return (
                                        <circle
                                          cx={cx}
                                          cy={cy}
                                          r={radius}
                                          fill={color}
                                          stroke={color}
                                          strokeWidth={2}
                                        />
                                      );
                                    }}
                                    connectNulls={false}
                                    name="信号强度"
                                  />
                                  <ReferenceLine
                                    y={-60}
                                    stroke="#52c41a"
                                    strokeDasharray="5 5"
                                    label="优秀信号"
                                  />
                                  <ReferenceLine
                                    y={-80}
                                    stroke="#faad14"
                                    strokeDasharray="5 5"
                                    label="良好信号"
                                  />
                                  <ReferenceLine
                                    y={-100}
                                    stroke="#ff4d4f"
                                    strokeDasharray="5 5"
                                    label="弱信号"
                                  />
                                  <Brush
                                    dataKey="time"
                                    height={30}
                                    stroke="#722ed1"
                                    alwaysShowText={true}
                                  />
                                </LineChart>
                              </ResponsiveContainer>
                            </div>
                          </Card>
                        ),
                      },
                    ]}
                  />
                </div>
              ) : (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description="暂无数据可视化"
                  style={{ padding: "60px 0" }}
                />
              )}
            </Spin>
          </div>
        )}
      </Modal>

      {/* 设备详情抽屉 */}
      <Drawer
        title={
          <Space>
            <SettingOutlined />
            设备详情 - {selectedDevice?.code}
          </Space>
        }
        width={800}
        open={detailDrawerVisible}
        onClose={() => setDetailDrawerVisible(false)}
        loading={detailLoading}
      >
        {selectedDevice && (
          <Space direction="vertical" size="large" style={{ width: "100%" }}>
            {/* 设备基本信息 */}
            <Card title="基本信息" size="small">
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Statistic
                    title="设备编号"
                    value={selectedDevice.code}
                    valueStyle={{ fontSize: 16 }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="样地编号"
                    value={selectedDevice.sample}
                    valueStyle={{ fontSize: 16 }}
                  />
                </Col>
                <Col span={8}>
                  <Statistic
                    title="批次号"
                    value={selectedDevice.batch}
                    valueStyle={{ fontSize: 16 }}
                  />
                </Col>
                <Col span={8}>
                  <div>
                    <Text type="secondary">设备类型</Text>
                    <div style={{ marginTop: 4 }}>
                      {getDeviceTypeTag(selectedDevice.type)}
                    </div>
                  </div>
                </Col>
                <Col span={8}>
                  <Statistic
                    title="创建时间"
                    value={
                      selectedDevice.updatedAt
                        ? formatTimestamp(selectedDevice.updatedAt)
                        : "-"
                    }
                    valueStyle={{ fontSize: 14 }}
                  />
                </Col>
              </Row>
            </Card>

            {/* 设备数据标签页 */}
            <Tabs
              items={[
                {
                  key: "deviceData",
                  label: (
                    <Space>
                      <DatabaseOutlined />
                      设备数据 ({deviceDataPagination.total || 0})
                    </Space>
                  ),
                  children: (
                    <Table
                      columns={[
                        {
                          title: "电压（V）",
                          dataIndex: "voltage",
                          key: "voltage",
                          width: 80,
                          render: (value) =>
                            value ? `${(value / 100).toFixed(2)}` : "-",
                        },
                        {
                          title: "测量值",
                          dataIndex: "mesa",
                          key: "mesa",
                          width: 100,
                        },
                        {
                          title: "角度",
                          dataIndex: "angle",
                          key: "angle",
                          width: 80,
                          render: (value) => (value ? `${value}°` : "-"),
                        },
                        {
                          title: "芯片温度（°C）",
                          dataIndex: "tmp",
                          key: "tmp",
                          width: 100,
                          render: (value) =>
                            value ? `${(value / 100).toFixed(1)}` : "-",
                        },
                        {
                          title: "信号强度（dBm）",
                          dataIndex: "rssi",
                          key: "rssi",
                          width: 100,
                          render: (value) => {
                            const color =
                              value > -60
                                ? "#52c41a"
                                : value > -80
                                ? "#faad14"
                                : "#f5222d";
                            return <Tag color={color}>{value}</Tag>;
                          },
                        },
                        {
                          title: "时间",
                          dataIndex: "updatedAt",
                          key: "updatedAt",
                          width: 150,
                          render: (updatedAt) =>
                            formatTimestamp(updatedAt, "YYYY-MM-DD HH:mm:ss"),
                        },
                      ]}
                      dataSource={deviceData}
                      rowKey="id"
                      size="small"
                      pagination={{
                        current: deviceDataPagination.current,
                        pageSize: deviceDataPagination.pageSize,
                        total: deviceDataPagination.total,
                        showSizeChanger: true,
                        showTotal: (total) => `共 ${total} 条`,
                        pageSizeOptions: ["10", "20", "50", "100"],
                      }}
                      onChange={handleDeviceDataTableChange}
                      scroll={{ x: 600 }}
                      locale={{
                        emptyText: (
                          <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="暂无设备传感器数据"
                          />
                        ),
                      }}
                    />
                  ),
                },
                {
                  key: "tempHumidity",
                  label: (
                    <Space>
                      <ExperimentOutlined />
                      温湿度 ({tempHumidityPagination.total || 0})
                    </Space>
                  ),
                  children: (
                    <Table
                      columns={[
                        {
                          title: "温度（°C）",
                          dataIndex: "temp",
                          key: "temp",
                          width: 100,
                          render: (value) =>
                            value ? `${(value / 100).toFixed(1)}` : "-",
                        },
                        {
                          title: "湿度（%）",
                          dataIndex: "humi",
                          key: "humi",
                          width: 100,
                          render: (value) =>
                            value ? `${(value / 100).toFixed(1)}` : "-",
                        },
                        {
                          title: "时间",
                          dataIndex: "simpletime",
                          key: "simpletime",
                          width: 150,
                          render: (timestamp) =>
                            formatTimestamp(timestamp, "YYYY-MM-DD HH:mm:ss"),
                        },
                      ]}
                      dataSource={tempHumidityData}
                      rowKey="id"
                      size="small"
                      pagination={{
                        current: tempHumidityPagination.current,
                        pageSize: tempHumidityPagination.pageSize,
                        total: tempHumidityPagination.total,
                        showSizeChanger: true,
                        showTotal: (total) => `共 ${total} 条`,
                        pageSizeOptions: ["10", "20", "50", "100"],
                      }}
                      onChange={handleTempHumidityTableChange}
                      locale={{
                        emptyText: (
                          <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="暂无温湿度数据"
                          />
                        ),
                      }}
                    />
                  ),
                },
                {
                  key: "params",
                  label: (
                    <Space>
                      <SettingOutlined />
                      设备参数 ({deviceParamsPagination.total || 0})
                    </Space>
                  ),
                  children: (() => {
                    if (!deviceParams || deviceParams.length === 0) {
                      return (
                        <Empty
                          image={Empty.PRESENTED_IMAGE_SIMPLE}
                          description="暂无设备参数数据"
                        />
                      );
                    }

                    return (
                      <div
                        style={{
                          maxHeight: "600px",
                          overflowY: "auto",
                          padding: "8px 0",
                        }}
                      >
                        {deviceParams.map((device, index) => {
                          let parsedParams = {};

                          try {
                            if (device.param) {
                              parsedParams = JSON.parse(device.param);
                            }
                          } catch (error) {
                            console.error("解析设备参数失败:", error);
                          }

                          // 参数项配置
                          const paramItems = [
                            {
                              key: "scanTime",
                              label: "扫描时间",
                              value: parsedParams.scanTime
                                ? `${parsedParams.scanTime}s`
                                : null,
                              icon: "⏱️",
                              color: "#4f46e5",
                              bgColor: "#f0f4ff",
                            },
                            {
                              key: "netOverTime",
                              label: "网络超时",
                              value: parsedParams.netOverTime
                                ? `${parsedParams.netOverTime}ms`
                                : null,
                              icon: "🌐",
                              color: "#059669",
                              bgColor: "#f0fdf4",
                            },
                            {
                              key: "waywakeup",
                              label: "唤醒间隔",
                              value: parsedParams.waywakeup
                                ? `${parsedParams.waywakeup}s`
                                : null,
                              icon: "⏰",
                              color: "#d97706",
                              bgColor: "#fffbeb",
                            },
                            {
                              key: "nextwakeup",
                              label: "下次唤醒",
                              value: parsedParams.nextwakeup
                                ? formatTimestamp(
                                    parsedParams.nextwakeup,
                                    "MM-DD HH:mm"
                                  )
                                : null,
                              icon: "⏳",
                              color: "#7c3aed",
                              bgColor: "#faf5ff",
                            },
                            {
                              key: "dbpower",
                              label: "发射功率",
                              value:
                                parsedParams.dbpower !== undefined
                                  ? `${parsedParams.dbpower}dBm`
                                  : null,
                              icon: "📶",
                              color:
                                parsedParams.dbpower > 10
                                  ? "#dc2626"
                                  : parsedParams.dbpower > 0
                                  ? "#ea580c"
                                  : "#16a34a",
                              bgColor:
                                parsedParams.dbpower > 10
                                  ? "#fef2f2"
                                  : parsedParams.dbpower > 0
                                  ? "#fff7ed"
                                  : "#f0fdf4",
                            },
                            {
                              key: "software",
                              label: "软件版本",
                              value: device.software
                                ? device.software.replace(/\u0000/g, "")
                                : null,
                              icon: "💾",
                              color: "#0891b2",
                              bgColor: "#f0f9ff",
                            },
                            {
                              key: "hardware",
                              label: "硬件版本",
                              value: device.hardware
                                ? device.hardware.replace(/\u0000/g, "")
                                : null,
                              icon: "🔧",
                              color: "#be185d",
                              bgColor: "#fdf2f8",
                            },
                            {
                              key: "imsi",
                              label: "IMSI",
                              value: device.imsi || null,
                              icon: "📱",
                              color: "#ea580c",
                              bgColor: "#fff7ed",
                            },
                          ].filter((item) => item.value);

                          return (
                            <div
                              key={device.id || `device_${index}`}
                              style={{
                                marginBottom: "24px",
                              }}
                            >
                              {/* 参数网格 - 直接显示参数 */}
                              <div
                                style={{
                                  display: "grid",
                                  gridTemplateColumns:
                                    "repeat(auto-fit, minmax(240px, 1fr))",
                                  gap: "16px",
                                }}
                              >
                                {paramItems.map((param) => (
                                  <div
                                    key={param.key}
                                    style={{
                                      background: param.bgColor,
                                      borderRadius: "12px",
                                      padding: "20px",
                                      border: `1px solid ${param.color}20`,
                                      transition: "all 0.3s ease",
                                      cursor: "default",
                                      boxShadow: "0 4px 16px rgba(0,0,0,0.05)",
                                    }}
                                    onMouseEnter={(e) => {
                                      e.currentTarget.style.transform =
                                        "translateY(-3px)";
                                      e.currentTarget.style.boxShadow = `0 12px 32px ${param.color}25`;
                                    }}
                                    onMouseLeave={(e) => {
                                      e.currentTarget.style.transform =
                                        "translateY(0)";
                                      e.currentTarget.style.boxShadow =
                                        "0 4px 16px rgba(0,0,0,0.05)";
                                    }}
                                  >
                                    <div
                                      style={{
                                        display: "flex",
                                        alignItems: "center",
                                        gap: "10px",
                                        marginBottom: "12px",
                                      }}
                                    >
                                      <span style={{ fontSize: "18px" }}>
                                        {param.icon}
                                      </span>
                                      <Text
                                        style={{
                                          fontSize: "13px",
                                          fontWeight: 600,
                                          color: "#6b7280",
                                          margin: 0,
                                          textTransform: "uppercase",
                                          letterSpacing: "0.8px",
                                        }}
                                      >
                                        {param.label}
                                      </Text>
                                    </div>
                                    <div
                                      style={{
                                        fontSize: "18px",
                                        fontWeight: 700,
                                        color: param.color,
                                        wordBreak: "break-all",
                                      }}
                                    >
                                      {param.key === "imsi" ? (
                                        <Text
                                          copyable={{ text: param.value }}
                                          style={{
                                            color: param.color,
                                            fontSize: "15px",
                                            fontFamily:
                                              'Monaco, Menlo, "Ubuntu Mono", monospace',
                                            fontWeight: 600,
                                          }}
                                        >
                                          {param.value}
                                        </Text>
                                      ) : (
                                        param.value
                                      )}
                                    </div>
                                  </div>
                                ))}
                              </div>

                              {/* 如果没有参数数据 */}
                              {paramItems.length === 0 && (
                                <div
                                  style={{
                                    padding: "60px 24px",
                                    textAlign: "center",
                                    color: "#9ca3af",
                                    background: "#f8f9fa",
                                    borderRadius: "12px",
                                    border: "1px dashed #d1d5db",
                                  }}
                                >
                                  <Text
                                    type="secondary"
                                    style={{ fontSize: "14px" }}
                                  >
                                    暂无参数数据
                                  </Text>
                                </div>
                              )}
                            </div>
                          );
                        })}
                      </div>
                    );
                  })(),
                },
                {
                  key: "originData",
                  label: (() => {
                    // 计算所有类型数据的总数
                    const totalCount = Object.values(originDataByType).reduce(
                      (sum, typeData) => sum + typeData.length,
                      0
                    );
                    return (
                      <Space>
                        <FileTextOutlined />
                        原始数据 ({totalCount})
                      </Space>
                    );
                  })(),
                  children: (() => {
                    // 定义所有的数据类型
                    const allTypes = [1, 2, 3, 4, 5, 6];

                    return (
                      <div>
                        {/* 统一显示批次号和设备编号 */}
                        {selectedDevice && (
                          <Card
                            size="small"
                            style={{
                              marginBottom: "16px",
                              backgroundColor: "#f8f9fa",
                            }}
                          >
                            <div style={{ textAlign: "center" }}>
                              <Space size="large">
                                <div>
                                  <Text
                                    strong
                                    style={{ fontSize: "12px", color: "#666" }}
                                  >
                                    批次号:
                                  </Text>
                                  <Text
                                    style={{
                                      marginLeft: "8px",
                                      fontSize: "16px",
                                      fontWeight: "bold",
                                      color: "#1890ff",
                                    }}
                                  >
                                    {selectedDevice.batch}
                                  </Text>
                                </div>
                                <Divider
                                  type="vertical"
                                  style={{ height: "20px" }}
                                />
                                <div>
                                  <Text
                                    strong
                                    style={{ fontSize: "12px", color: "#666" }}
                                  >
                                    设备编号:
                                  </Text>
                                  <Text
                                    style={{
                                      marginLeft: "8px",
                                      fontSize: "16px",
                                      fontWeight: "bold",
                                      color: "#1890ff",
                                    }}
                                  >
                                    {selectedDevice.code}
                                  </Text>
                                </div>
                              </Space>
                            </div>
                          </Card>
                        )}

                        <Tabs
                          type="card"
                          size="small"
                          activeKey={activeOriginTab}
                          onChange={(activeKey) => {
                            setActiveOriginTab(activeKey);
                            // 当切换到某个tab时，触发数据请求
                            const type = parseInt(
                              activeKey.replace("type-", "")
                            );
                            if (selectedDevice && allTypes.includes(type)) {
                              // 避免重复请求：如果正在加载或已有数据，则不请求
                              const isLoading = originDataLoading[type];
                              const hasData =
                                originDataByType[type] &&
                                originDataByType[type].length > 0;
                              if (!isLoading && !hasData) {
                                fetchOriginDataByType(selectedDevice, type);
                              }
                            }
                          }}
                          items={allTypes.map((type) => {
                            const typeData = originDataByType[type] || [];
                            const isLoading = originDataLoading[type] || false;

                            return {
                              key: `type-${type}`,
                              label: (
                                <Space size="small">
                                  {getOriginDataTypeTag(type)}
                                  <Text type="secondary">
                                    ({typeData.length})
                                  </Text>
                                  {activeOriginTab === `type-${type}` &&
                                    (isLoading ? (
                                      <span style={{ color: "#1890ff" }}>
                                        ⟳
                                      </span>
                                    ) : (
                                      <ReloadOutlined
                                        style={{
                                          color: "#666",
                                          fontSize: "12px",
                                          cursor: "pointer",
                                          padding: "2px",
                                        }}
                                        onClick={(e) => {
                                          e.stopPropagation(); // 防止触发tab切换
                                          if (selectedDevice) {
                                            fetchOriginDataByType(
                                              selectedDevice,
                                              type,
                                              true
                                            );
                                          }
                                        }}
                                        onMouseEnter={(e) => {
                                          e.target.style.color = "#1890ff";
                                        }}
                                        onMouseLeave={(e) => {
                                          e.target.style.color = "#666";
                                        }}
                                        title={`刷新${
                                          getOriginDataTypeTag(type).props
                                            .children
                                        }数据`}
                                      />
                                    ))}
                                </Space>
                              ),
                              children: (
                                <div
                                  style={{
                                    maxHeight: "1000px",
                                    overflowY: "auto",
                                    padding: "16px 0",
                                  }}
                                >
                                  {isLoading ? (
                                    <div
                                      style={{
                                        textAlign: "center",
                                        padding: "60px 20px",
                                        color: "#666",
                                      }}
                                    >
                                      <div
                                        style={{
                                          fontSize: "24px",
                                          marginBottom: "16px",
                                        }}
                                      >
                                        ⟳
                                      </div>
                                      <Text type="secondary">
                                        正在加载数据...
                                      </Text>
                                    </div>
                                  ) : typeData.length === 0 ? (
                                    <Empty
                                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                                      description={`暂无${
                                        getOriginDataTypeTag(type).props
                                          .children
                                      }数据`}
                                    />
                                  ) : (
                                    typeData.map((item, index) => (
                                      <Card
                                        key={
                                          item.id || `origin-${type}-${index}`
                                        }
                                        size="small"
                                        title={
                                          <Space>
                                            <Text strong>
                                              数据 #{index + 1}
                                            </Text>
                                            <Text type="secondary">
                                              {formatTimestamp(
                                                item.updatedAt,
                                                "YYYY-MM-DD HH:mm:ss"
                                              )}
                                            </Text>
                                          </Space>
                                        }
                                        style={{
                                          marginBottom: "16px",
                                          borderRadius: "8px",
                                        }}
                                        extra={
                                          <Space>
                                            <Badge
                                              count={
                                                item.uploadData?.length || 0
                                              }
                                              overflowCount={Infinity}
                                              style={{
                                                backgroundColor: "#108ee9",
                                              }}
                                            />
                                            <Text type="secondary">bytes</Text>
                                            <Button
                                              type="text"
                                              size="small"
                                              icon={<CopyOutlined />}
                                              onClick={() =>
                                                copyToClipboard(
                                                  formatHexData(item.uploadData)
                                                )
                                              }
                                              title="复制十六进制数据"
                                              style={{
                                                padding: "2px 4px",
                                                minWidth: "auto",
                                                height: "auto",
                                              }}
                                            />
                                          </Space>
                                        }
                                      >
                                        <div style={{ width: "100%" }}>
                                          <Text
                                            strong
                                            style={{
                                              fontSize: "12px",
                                              color: "#666",
                                              marginBottom: "8px",
                                              display: "block",
                                            }}
                                          >
                                            原始数据 (HEX):
                                          </Text>
                                          <div
                                            style={{
                                              background: "#f8f9fa",
                                              border: "1px solid #e9ecef",
                                              borderRadius: "6px",
                                              padding: "12px",
                                              fontFamily:
                                                'Monaco, Menlo, "Ubuntu Mono", monospace',
                                              fontSize: "13px",
                                              lineHeight: "1.6",
                                              wordBreak: "break-all",
                                              maxHeight: "200px",
                                              overflowY: "auto",
                                            }}
                                          >
                                            <Text
                                              style={{
                                                color: "#2563eb",
                                                fontWeight: "500",
                                              }}
                                            >
                                              {formatHexData(item.uploadData)}
                                            </Text>
                                          </div>
                                        </div>
                                      </Card>
                                    ))
                                  )}
                                </div>
                              ),
                            };
                          })}
                        />
                      </div>
                    );
                  })(),
                },
                // CMD指令管理 tab - 仅网关设备显示
                ...(selectedDevice && selectedDevice.type === 2
                  ? [
                      {
                        key: "cmd",
                        label: (
                          <Space>
                            <CodeOutlined />
                            CMD指令 ({cmdPagination.total || 0})
                          </Space>
                        ),
                        children: (
                          <div>
                            <div style={{ marginBottom: 16 }}>
                              <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={showCmdModal}
                              >
                                添加指令
                              </Button>
                            </div>
                            <Table
                              columns={[
                                {
                                  title: "指令内容 (HEX)",
                                  dataIndex: "uploadData",
                                  key: "uploadData",
                                  render: (uploadData) => {
                                    const hexString = formatHexData(uploadData);
                                    return (
                                      <div
                                        style={{
                                          display: "flex",
                                          alignItems: "center",
                                          gap: "8px",
                                        }}
                                      >
                                        <Text
                                          code
                                          style={{
                                            fontFamily:
                                              'Monaco, Menlo, "Ubuntu Mono", monospace',
                                            fontSize: "13px",
                                          }}
                                        >
                                          {hexString}
                                        </Text>
                                        <Button
                                          type="text"
                                          size="small"
                                          icon={<CopyOutlined />}
                                          onClick={() =>
                                            copyToClipboard(hexString)
                                          }
                                          title="复制"
                                          style={{ padding: "2px 4px" }}
                                        />
                                      </div>
                                    );
                                  },
                                },
                                {
                                  title: "批次号",
                                  dataIndex: "batch",
                                  key: "batch",
                                  width: 100,
                                },
                                {
                                  title: "设备编号",
                                  dataIndex: "code",
                                  key: "code",
                                  width: 100,
                                },
                                {
                                  title: "时间",
                                  dataIndex: "updatedAt",
                                  key: "updatedAt",
                                  width: 180,
                                  render: (updatedAt) =>
                                    formatTimestamp(
                                      updatedAt,
                                      "YYYY-MM-DD HH:mm:ss"
                                    ),
                                },
                                {
                                  title: "操作",
                                  key: "action",
                                  width: 100,
                                  render: (_, record) => (
                                    <Popconfirm
                                      title="确定删除该指令吗？"
                                      onConfirm={() =>
                                        handleDeleteCmd(record.id)
                                      }
                                      okText="确定"
                                      cancelText="取消"
                                    >
                                      <Button
                                        type="link"
                                        danger
                                        size="small"
                                        icon={<DeleteOutlined />}
                                      >
                                        删除
                                      </Button>
                                    </Popconfirm>
                                  ),
                                },
                              ]}
                              dataSource={cmdList}
                              rowKey="id"
                              size="small"
                              loading={cmdLoading}
                              pagination={{
                                current: cmdPagination.current,
                                pageSize: cmdPagination.pageSize,
                                total: cmdPagination.total,
                                showSizeChanger: true,
                                showTotal: (total) => `共 ${total} 条`,
                                pageSizeOptions: ["10", "20", "50", "100"],
                              }}
                              onChange={handleCmdTableChange}
                              locale={{
                                emptyText: (
                                  <Empty
                                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                                    description="暂无指令数据"
                                  />
                                ),
                              }}
                            />
                          </div>
                        ),
                      },
                    ]
                  : []),
              ]}
            />
          </Space>
        )}
      </Drawer>

      {/* CMD指令添加模态框 */}
      <Modal
        title="添加指令"
        open={cmdModalVisible}
        onOk={handleCmdSubmit}
        onCancel={handleCmdModalCancel}
        okText="发送"
        cancelText="取消"
      >
        <Form form={cmdForm} layout="vertical">
          <Form.Item
            name="cmd"
            label="指令内容 (16进制)"
            rules={[
              { required: true, message: "请输入指令内容" },
              {
                validator: (_, value) => {
                  if (!value) {
                    return Promise.resolve();
                  }
                  if (!isValidHex(value)) {
                    return Promise.reject(
                      new Error(
                        "指令格式不正确，只能包含0-9和a-f/A-F字符（如：0a0b）"
                      )
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input
              placeholder="请输入16进制指令，如：0a0b"
              style={{
                fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
              }}
              onChange={(e) => {
                // 转换为小写
                const value = e.target.value.toLowerCase();
                cmdForm.setFieldsValue({ cmd: value });
              }}
            />
          </Form.Item>
          <div style={{ color: "#999", fontSize: "12px", marginTop: -8 }}>
            提示：请输入有效的16进制数据，只能包含数字0-9和字母a-f（如：0a0b、1a2b3c4d）
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default DeviceManagement;
